from flask import Flask, jsonify
from flask_restful import Api, Resource
import mysql.connector
from flask_cors import CORS
app = Flask(__name__)
api = Api(app)
CORS(app)
# 数据库连接配置
db_config = {
    'host': 'localhost',
    'user': 'root',
    'port': 3307,
    'password': '123456',
    'database': 'bookschema'
}

# 创建数据库连接
db_connection = mysql.connector.connect(**db_config)
cursor = db_connection.cursor()

class BookResource(Resource):
    def get(self):
        # 查询数据库中的所有书籍信息
        cursor.execute("SELECT * FROM books")
        books = cursor.fetchall()

        # 将查询结果转换为字典列表
        book_list = []
        for book in books:
            book_dict = {
                'itemId': book[0],
                'title': book[1],
                'author': book[2],
                'description': book[3],
                'quantity':book[4],
                'price':book[5],
                'type':book[6]
            }
            book_list.append(book_dict)

        return jsonify({'books': book_list})

# 将资源添加到 API 中
api.add_resource(BookResource, '/books')

if __name__ == '__main__':
    app.run(debug=True)

